import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'

import layout from '@/views/layout'
import home from '@/views/Home'
import ask from '@/views/Ask'
import video from '@/views/Video'
import mine from '@/views/Mine'
import edit from '@/views/Mine/edit'
import articleDetail from '@/views/Home/articleDetail'
import search from '@/views/Search'
import result from '@/views/Search/result.vue'
import chat from '@/views/Mine/chat'

import store from '@/store'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
    { name: 'login', path: '/login', component: login },
    { path: '/', redirect: '/login' },
    {
        name: 'layout',
        path: '/layout',
        component: layout,
        children: [
          { name: 'home', path: 'home', component: home ,meta:{keepAlive:true}},
          { name: 'ask', path: 'ask', component: ask },
          { name: 'video', path: 'video', component: video },
          { name: 'mine', path: 'mine', component: mine,meta: {
            needLogin: true
          } },
        ]
      },
      { name:'edit', path: '/mine/edit', component: edit},
      { name:'articleDetail', path: '/home/articleDetail/:id', component: articleDetail},
      { name: 'search', path: '/search', component: search },
      { name: 'result', path: '/search/result', component: result },
      { name: 'chat', path: '/mine/chat', component: chat },
    ]

const router = new VueRouter({
  routes
})

// 全局前置守卫
router.beforeEach((to,from,next)=>{
    if(to.meta.needLogin){
        // 代表去的是要登录的页面
        if(store.state.tokenObj.token){
            next()
        }else{
            Toast.fail('请先登录')
            //没有登录
            next({
                name: 'login',
                query: {
                  back: to.path // 记录原本要去的页面路径
                }
              })
        }
    }else{
        // 代表去的是不需要登录就能访问的页面
        next()
    }
})

export default router